package com.tdk.wifidirectserver

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.tdk.wifidirectserver.ui.main.ConnectedClientFragment
import com.tdk.wifidirectserver.ui.main.ConnectedServerFragment
import com.tdk.wifidirectserver.ui.main.MainFragment
import com.tdk.wifidirectserver.ui.main.MainViewModel

class MainActivity : AppCompatActivity() {
    val TAG = "MainActivity"
    lateinit var viewModel: MainViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        viewModel = ViewModelProvider(this)[MainViewModel::class.java]
        viewModel.mediatorLiveData.observe(this) {
            Log.d(TAG, "onCreate:mediatorLiveData:$it")
            var isConnected = it.first
            var connectedWifiP2pDevice = it.second
            if (isConnected) {
                Log.d(TAG, "onCreate:isConnected:$it")
                Log.d(TAG, "onCreate:connectedWifiP2pDevice:$connectedWifiP2pDevice")
                if (connectedWifiP2pDevice != null && connectedWifiP2pDevice.groupFormed) {
                    if (connectedWifiP2pDevice.isGroupOwner) {
                        supportFragmentManager.beginTransaction()
                            .replace(R.id.container, ConnectedServerFragment.newInstance(), "ConnectedFragment")
                            .commitNow()
                    } else {
                        supportFragmentManager.beginTransaction()
                            .replace(R.id.container, ConnectedClientFragment.newInstance(), "ConnectedFragment")
                            .commitNow()
                    }
                }
            } else {
                supportFragmentManager.beginTransaction()
                    .replace(R.id.container, MainFragment.newInstance(), "MainFragment")
                    .commitNow()
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        viewModel.unregisterReceiver()
    }
}